/**
 * Created by Wind on 2017/10/13.
 */
/**
 * List of tab names.
 * @private
 */

function get_board() {  //获取当前连接板子的类型
  var url = "http://" + window.location.host + '/select_board/';
  var method = "GET";
  var async = true;
  var request = new XMLHttpRequest();
  request.onreadystatechange = function () {
    if (request.readyState != 4) {
      return;
    }
    var status = parseInt(request.status); // HTTP response status, e.g., 200 for "200 OK"
    if (status == 200) {
      var body = request.responseText;
      var a_list = $("li.board").find("a");
      for (var i = 0; i < a_list.length; i++) {
        var value = a_list[i].getAttribute('value');
        if (value == body) {
          $(a_list[i]).parent('li').find("i").css("display", "block");
        }
        else {
          $(a_list[i]).parent('li').find("i").css("display", "none");
        }
      }
    }
  };
  request.open(method, url, async);
  request.send();
}

/**
 * Initialize Blockly.  Called on page load.
 */
var workspace = null;

function start() {

  // Setup blocks
  // Parse the URL arguments.
  var match = location.search.match(/dir=([^&]+)/);
  var rtl = match && match[1] == 'rtl';
  //document.forms.options.elements.dir.selectedIndex = Number(rtl);
  var toolbox = toolboxXml();
  //document.forms.options.elements.toolbox.selectedIndex =
  //toolbox ? 1: 0;

  match = location.search.match(/side=([^&]+)/);

  var side = match ? match[1] : 'start';

  //document.forms.options.elements.side.value = side;

  //Create main workspace.
  workspace = Blockly.inject('content_blocks', {
    comments: false,
    disable: false,
    collapse: false,
    media: '../../../blockly/media/',
    readOnly: false,
    rtl: rtl,
    scrollbars: true,
    toolbox: toolbox,
    toolboxPosition: side == 'top' || side == 'start' ? 'start' : 'end',
    horizontalLayout: side == 'top' || side == 'bottom',
    //sounds: soundsEnabled,
    grid:
      {
        spacing: 20,
        length: 3,
        colour: '#ccc',
        snap: true
      },
    zoom: {
      controls: true,
      wheel: true,
      startScale: 0.72,
      maxScale: 4,
      minScale: 0.25,
      scaleSpeed: 1.1
    },
    colours: {
      fieldShadow: 'rgba(255, 255, 255, 10)',
      dragShadowOpacity: 0.6
    },
    trashcan: true
  });
  get_board();
  get_connect_type();
  window.setInterval(function () {
    check_connect_state();
  },1000);
  var loadInput = document.getElementById('load');
  loadInput.addEventListener('change', load, false);
  document.getElementById('fakeload').onclick = function () {
    loadInput.click();
  };
}

function getToolboxElement() {
  var match = location.search.match(/toolbox=([^&]+)/);
  return document.getElementById('toolbox-' + (match ? match[1] : 'simple'));
}

function check_connect_state(){ //检测板子的连接状态
  var connect_type="0";

  var a_list = $("li.board-connect").find("a");
  for (var i = 0; i < a_list.length; i++) {
    var value = a_list[i].getAttribute('value');
    var qtype=$(a_list[i]).parent('li').find("i").css("display");
    if(qtype=="block"){
      connect_type=value
    }
  }

  var url = "http://" + window.location.host + '/port_connect_status/?connect_type='+connect_type;
  var method = "GET";
  var async = true;
  var request = new XMLHttpRequest();
  request.onreadystatechange = function () {
    if (request.readyState != 4) {
      return;
    }
    var status = parseInt(request.status); // HTTP response status, e.g., 200 for "200 OK"
    if (status == 200) {
      var body = request.responseText;
      if(body=="1"){
        if($(".connect_state").attr("title")!="成功连接到arduino"){
          $(".connect_state").attr("src","/blockly/apps/blocklyduino/img/lv.png");
          $(".connect_state").attr("title","成功连接到arduino")
        }
      }
      else{
        if($(".connect_state").attr("title")!="未连接到arduino"){
          $(".connect_state").attr("src","/blockly/apps/blocklyduino/img/hong.png");
          $(".connect_state").attr("title","未连接到arduino");
        }
      }
    }
    else{
      if($(".connect_state").attr("title")!="未连接到arduino"){
          $(".connect_state").attr("src","/blockly/apps/blocklyduino/img/hong.png");
          $(".connect_state").attr("title","未连接到arduino");
        }
    }
  };
  request.open(method, url, async);
  request.send();
}

function get_connect_type() {   //换取板子上一次连接方式
  var url = "http://" + window.location.host + '/get_connect_type/';
  var method = "GET";
  var async = true;
  var request = new XMLHttpRequest();
  request.onreadystatechange = function () {
    if (request.readyState != 4) {
      return;
    }
    var status = parseInt(request.status); // HTTP response status, e.g., 200 for "200 OK"
    if (status == 200) {
      var body = request.responseText;
      var state=body.split(";")[0];
      var ip="";
      if(body.split(";").length>1) {
        ip = body.split(";");
      }
      var a_list = $("li.board-connect").find("a");
      for (var i = 0; i < a_list.length; i++) {
        var value = a_list[i].getAttribute('value');
        if (value == state) {
          $(a_list[i]).parent('li').find("i").css("display", "block");
          if(value=="2"){
            $(a_list[i]).text("wifi连接 ip:"+ip)
          }
        }
        else {
          $(a_list[i]).parent('li').find("i").css("display", "none");
        }
      }
    }
  };
  request.open(method, url, async);
  request.send();
}


  function select_board_connect_type(el) {
    var connect = el.getAttribute("value");
    var parent_el = $(el).parent("li");
    var ul_parent_el = $(el).parent("li").parent("ul");
    post_board_connect_type(connect, function (status, errorInfo) {
      if (status == 200) {
        ul_parent_el.find("i").css("display", "none");
        parent_el.find("i").css("display", "block");
        alert("选择连接方式成功");
      } else {
        alert("选择连接方式失败: " + errorInfo);
      }
    });
  }

  function post_board_connect_type(code, callback) {

    var url = "http://" + window.location.host + '/select_board_connect_type/';
    var method = "POST";

// You REALLY want async = true.
// Otherwise, it'll block ALL execution waiting for server response.
    var async = true;

    var request = new XMLHttpRequest();


    request.onreadystatechange = function () {
      if (request.readyState != 4) {
        return;
      }
      var status = parseInt(request.status); // HTTP response status, e.g., 200 for "200 OK"
      var errorInfo = null;
      switch (status) {
        case 200:
          break;
        case 0:
          errorInfo = "code 0\n\n 不能连接到服务器 " + url + ".  请确认服务器是否允许?";
          break;
        case 400:
          errorInfo = "code 400\n\n选择连接方式失败.";
          break;
        case 500:
          errorInfo = "code 500\n\n选择连接方式失败，服务器内部错误. ";
          break;
        case 501:
          errorInfo = "code 501\n\n选择连接方式失败，服务器内部错误.";
          break;
        default:
          errorInfo = "code " + status + "\n\n未知错误.";
          break;
      }
      ;

      callback(status, errorInfo);
    };

    request.open(method, url, async);
    request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    request.send(code);
  }

